package com.soup.fs.dao;

import com.soup.fs.bean.Node;
import com.soup.fs.bean.Storage;

import java.sql.*;
import java.util.List;

public class FileDao {

    static {
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private Connection connection = null;

    public FileDao(){
        try {
            connection = DriverManager.getConnection("jdbc:sqlite:soup-fs/db/fs.db");
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 添加一个文件
     * @param storage
     */
    public void insert(Storage storage) throws Exception{

        PreparedStatement preparedStatement =
                connection.prepareStatement("insert into node values (?,?,?)");
        List<Node> nodes = storage.getNodes();

        for (Node node : nodes) {
            preparedStatement.setString(1, node.getNodeId());
            preparedStatement.setString(2, storage.getFileId());
            preparedStatement.setString(3, node.getPath());
            preparedStatement.executeUpdate();
        }

        PreparedStatement statement =
                connection.prepareStatement("insert into storage values (?,?,?,?)");
        statement.setString(1,storage.getFileId());
        statement.setString(2,storage.getName());
        statement.setString(3,storage.getSuffix());
        statement.setString(4,storage.getMeta());
        statement.executeUpdate();
    }

    public Storage query(String fileId) throws SQLException{
        Storage storage = new Storage();
        List<Node> nodes = storage.getNodes();

        PreparedStatement statement =
                connection.prepareStatement("select * from node where fileId=?");
        statement.setString(1,fileId);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            nodes.add(new Node(resultSet.getString("nodeId"),
                    resultSet.getString("path")));
        }

        PreparedStatement ops =
                connection.prepareStatement("select * from storage where fileId=? limit 1");
        ops.setString(1,fileId);
        ResultSet opsResult = ops.executeQuery();
        if (opsResult.next()) {
            storage.setFileId(opsResult.getString("fileId"));
            storage.setName(opsResult.getString("name"));
            storage.setSuffix(opsResult.getString("suffix"));
            storage.setMeta(opsResult.getString("meta"));
            return storage;
        }
        return null;
    }

}
